<?php

namespace app\order\logic;

use app\data\util\HttpUtil;
use think\facade\Db;
use think\facade\Cache;
use util\Excel;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;

class OrderCheckSpuLogic
{
    protected $model = null;
    public function __construct()
    {
        $this->model = new \app\order\model\OrderCheckSpu();
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {
        $date  = $params['date'] ?? [];
        $type  = $params['type'] ?? [];
        $spu   = $params['spu'] ?? [];
        $limit = $params['limit'] ?? 10;
        $where = [];
        
        if(!empty($type)){
            $where['type'] = $type;
        }
        if(!empty($date)){
            $where['date'] = $date;
        }

        if($spu){
            $where[] = ['spu','=',$spu];
        }


        $list = Db::name('ordercheck_spucost')
            ->where($where)
            ->order("timedate desc,id asc")
            ->paginate($limit);

        $lists = $list->items();
        $spus           = array_column($lists,'spu');
        //批量获取图片地址;
        $products     = Db::name('product')->field('spu,product_images')->whereIn('spu',$spus)->select()->toArray();
        $products_map = array_column($products,null,'spu');
        foreach($lists as $k=>$v){
            $spu                 = strtolower($v['spu']);
            $product_images      = $products_map[$spu]??[];
            $product_images_info = $product_images['product_images']??[];
            $current_images = $product_images_info ? current(json_decode($product_images_info)) : '';
            $lists[$k]['product_images'] = $current_images;
        }

                
        $data = [
            'list' => $lists,
            'total' => $list->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导出
     * @author zhangheng
     */
    public function export($params = [])
    {
        $header = [];
        $header[] = ['ID', 'id'];
        $header[] = ['月份', 'date'];
        $header[] = ['SPU', 'spu'];
        $header[] = ['单价（RMB）', 'material'];
        $fileName = "export_Advaccount" . time();
        
        $date  = $params['date'] ?? [];
        $type  = $params['type'] ?? [];
        $spu   = $params['spu'] ?? [];
        $where = [];
        
        if(!empty($type)){
            $where['type'] = $type;
        }
        if(!empty($date)){
            $where['date'] = $date;
        }

        if($spu){
            $where[] = ['spu','=',$spu];
        }

        $lists = Db::name('ordercheck_spucost')
            ->where($where)
            ->order("timedate desc,id asc")
            ->select()->toarray();

        foreach($lists as $k=>$v){
            $spu = strtolower($v['spu']);
        }

        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }

    public function find($id)
    {
        if (!$id) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $row = $this->model->find($id);
        
        if (empty($row)) {
            return json(DefaultResponse(201, false, '数据不存在!', null));
        }

        return json(DefaultResponse(200, true, '获取成功', $row));
    }

    public function edit($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $result = false;
        try {
            
            foreach ($data as $value) {  
                $updateData = [
                    'material' => $value["material"] ?? 0,
                ];
                table('ordercheck_spucost')
                    ->where('id', $value['id'])
                    ->update($updateData);
            }

            $result = true;
            
            if ($result) {
                return json(DefaultResponse(200, false, '更新成功!', null));
            }
            return json(DefaultResponse(201, false, '更新失败!', null));
        } catch (ValidateException $e) {
            return json(DefaultResponse(201, false, $e->getError(), null));
        } catch (\Exception $e) {
            return json(DefaultResponse(201, false, '更新失败!', null));
        }
        return json(DefaultResponse(200, false, '更新成功!', null));
    }

    
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导入
     * @author zhangheng
     */
    public function uploads($file="")
    {
        if(!empty($file)){
            $upload = new Upload();
            $res = $upload->upload($file);
            if ($res['url']) {
                $return = $this->import_cost($res['url']);
                return json(DefaultResponse(200, true, '操作成功', $return));
            } else {
                return json(DefaultResponse(201, true, '上传文件失败', $res['msg']));
            }
        }else{
            return json(DefaultResponse(201, true, '文件为空'));
        }
    }

    //导入花费
    public function import_cost($url)
    {
        $url_arr = explode('storage/', $url);
        $data = Excel::import('storage/' . $url_arr[1]);
        foreach ($data[0] as $key=>$value) {
            if($key == 1){
                continue;
            }
            $updateData['material'] = $value[3] ?? 0;
            Db::name('ordercheck_spucost')
                ->where('id', $value[0])
                ->update($updateData);
        }
        return $url;
    }
    
    
}
